package com.zxq.memory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

public class ByteArrayPools {

    public static ConcurrentHashMap<String, ConcurrentLinkedQueue<byte[]>> hashLinkMap = new ConcurrentHashMap<>();

    /**
     * 根据长度，获取对应的byte[]数组
     * @param len
     * @return
     */
    public static byte[] getBytes(String len) {
        ConcurrentLinkedQueue<byte[]> queue = null;
        if(hashLinkMap.get(len) == null) {
            queue = new ConcurrentLinkedQueue();
            hashLinkMap.put(len,queue);
        }
        queue = hashLinkMap.get(len);
        byte[] buff =  queue.poll();
        if(buff == null) {
            buff = new byte[Integer.parseInt(len)];
        }
        return buff;
    }

    /**
     * 回收对应的byte[]数组
     * @param array
     */
    public static void recycle(byte[] array) {
        String len = array.length + "";
        for(int i =0; i < array.length; i++) {
            array[i] = 0x00;
        }
        ConcurrentLinkedQueue<byte[]> queue =  hashLinkMap.get(len);
        queue.offer(array);
    }




}
